import React, { useState, useEffect } from "react";
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  message,
  Popconfirm,
  Switch,
  Space,
} from "antd";
import {
  getUserList,
  addUser,
  deleteUser,
  updateUserStatus,
} from "../../api/user";

const { Option } = Select;

/**
 * UserManagement 组件
 * 用于管理用户列表，包括查看、添加、删除、启用/停用用户等功能
 */
const UserManagement = () => {
  // 用户列表数据
  const [users, setUsers] = useState([]);
  // 控制添加用户模态框的显示
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 控制停用用户模态框的显示
  const [isDisableModalVisible, setIsDisableModalVisible] = useState(false);
  // 当前正在停用的用户ID
  const [disablingUserId, setDisablingUserId] = useState(null);
  // 停用原因
  const [disableReason, setDisableReason] = useState("");
  // 添加用户表单实例
  const [form] = Form.useForm();
  // 控制加载状态
  const [isLoading, setIsLoading] = useState(false);
  // 停用用户表单实例
  const [disableForm] = Form.useForm();
  // 筛选条件
  const [filters, setFilters] = useState({
    username: "",
    role: "",
    loginSystem: "",
  });

  // 组件挂载时获取用户列表
  useEffect(() => {
    fetchUsers();
  }, []);

  /**
   * 获取用户列表
   */
  const fetchUsers = async () => {
    setIsLoading(true);
    try {
      const response = await getUserList(filters);
      setUsers(response.data);
    } catch (error) {
      message.error("获取用户列表失败");
    }
    setIsLoading(false);
  };

  /**
   * 显示添加用户模态框
   */
  const showModal = () => {
    setIsModalVisible(true);
  };

  /**
   * 关闭添加用户模态框
   */
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  /**
   * 处理添加用户
   * @param {Object} values - 表单值
   */
  const handleAddUser = async (values) => {
    try {
      await addUser(values);
      message.success("添加用户成功");
      setIsModalVisible(false);
      form.resetFields();
      fetchUsers();
    } catch (error) {
      message.error("添加用户失败");
    }
  };

  /**
   * 处理删除用户
   * @param {string} userId - 用户ID
   */
  const handleDeleteUser = async (userId) => {
    try {
      await deleteUser(userId);
      message.success("删除用户成功");
      fetchUsers();
    } catch (error) {
      message.error("删除用户失败");
    }
  };

  /**
   * 处理用户状态变更
   * @param {boolean} checked - 开关状态
   * @param {string} userId - 用户ID
   */
  const handleStatusChange = async (checked, userId) => {
    if (!checked) {
      setDisablingUserId(userId);
      setIsDisableModalVisible(true);
      setDisableReason("");
      disableForm.resetFields();
    } else {
      try {
        await updateUserStatus(userId, 1);
        message.success("启用用户成功");
        fetchUsers();
      } catch (error) {
        message.error("启用用户失败");
      }
    }
  };

  /**
   * 确认停用用户
   */
  const handleDisableConfirm = async () => {
    try {
      const values = await disableForm.validateFields();
      await updateUserStatus(disablingUserId, 0, values.disableReason);
      message.success("停用用户成功");
      setIsDisableModalVisible(false);
      setDisableReason("");
      disableForm.resetFields();
      fetchUsers();
    } catch (error) {
      if (error.errorFields) {
        message.error("请输入停用原因");
      } else {
        message.error("停用用户失败");
      }
    }
  };

  /**
   * 取消停用用户
   */
  const handleDisableCancel = () => {
    setIsDisableModalVisible(false);
    setDisableReason("");
    disableForm.resetFields();
    fetchUsers();
  };

  /**
   * 停用模态框关闭后的处理
   */
  const handleDisableModalClose = () => {
    setDisableReason("");
    disableForm.resetFields();
  };

  // 同步停用原因和表单字段
  useEffect(() => {
    if (isDisableModalVisible) {
      disableForm.setFieldsValue({ disableReason });
    }
  }, [disableReason, isDisableModalVisible, disableForm]);

  /**
   * 处理筛选条件变化
   * @param {string} name - 筛选字段名
   * @param {string} value - 筛选值
   */
  const handleFilterChange = (name, value) => {
    setFilters((prevFilters) => ({
      ...prevFilters,
      [name]: value,
    }));
  };

  /**
   * 处理查询按钮点击
   */
  const handleSearch = () => {
    fetchUsers();
  };

  // 表格列定义
  const columns = [
    {
      title: "用户名",
      dataIndex: "username",
      key: "username",
    },
    {
      title: "角色",
      dataIndex: "role",
      key: "role",
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "最后登录时间",
      dataIndex: "lastLoginTime",
      key: "lastLoginTime",
    },
    {
      title: "最后登录IP",
      dataIndex: "lastLoginIp",
      key: "lastLoginIp",
    },
    {
      title: "登录系统权限",
      dataIndex: "loginSystem",
      key: "loginSystem",
      render: (loginSystem) => {
        const systemMap = {
          1: "仅CMS后台",
          2: "仅C端前台",
          3: "CMS后台和C端前台",
        };
        return systemMap[loginSystem] || "未知";
      },
    },
    {
      title: "状态",
      dataIndex: "status",
      key: "status",
      render: (status, record) => (
        <Switch
          checked={status === 1}
          onChange={(checked) => handleStatusChange(checked, record.userId)}
        />
      ),
    },
    {
      title: "停用原因",
      dataIndex: "disableReason",
      key: "disableReason",
      render: (disableReason, record) => {
        if (record.status === 0) return <span>{disableReason}</span>;
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <span>
          <Popconfirm
            title="确定要删除此用户吗？"
            onConfirm={() => handleDeleteUser(record.userId)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link">删除</Button>
          </Popconfirm>
        </span>
      ),
    },
  ];

  return (
    <div>
      {/* 筛选、查询和新增用户按钮 */}
      <Space style={{ marginBottom: 16 }}>
        <Input
          placeholder="用户名"
          value={filters.username}
          onChange={(e) => handleFilterChange("username", e.target.value)}
        />
        <Select
          style={{ width: 120 }}
          placeholder="角色"
          value={filters.role}
          onChange={(value) => handleFilterChange("role", value)}
        >
          <Option value="">全部</Option>
          <Option value="USER">用户</Option>
          <Option value="ADMIN">管理员</Option>
        </Select>
        <Select
          style={{ width: 200 }}
          placeholder="登录系统权限"
          value={filters.loginSystem}
          onChange={(value) => handleFilterChange("loginSystem", value)}
        >
          <Option value="">全部</Option>
          <Option value="1">仅CMS后台</Option>
          <Option value="2">仅C端前台</Option>
          <Option value="3">CMS后台和C端前台</Option>
        </Select>
        <Button type="primary" onClick={handleSearch}>
          查询
        </Button>
        <Button onClick={showModal}>新增用户</Button>
      </Space>

      {/* 用户列表表格 */}
      <Table
        columns={columns}
        dataSource={users}
        rowKey="userId"
        loading={isLoading}
      />

      {/* 新增用户模态框 */}
      <Modal
        title="新增用户"
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={null}
      >
        <Form form={form} onFinish={handleAddUser} layout="vertical">
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: "请输入用户名" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            rules={[{ required: true, message: "请输入密码" }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item
            name="role"
            label="角色"
            rules={[{ required: true, message: "请选择角色" }]}
          >
            <Select>
              <Option value="USER">用户</Option>
              <Option value="ADMIN">管理员</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="loginSystem"
            label="登录系统权限"
            rules={[{ required: true, message: "请选择登录系统权限" }]}
          >
            <Select>
              <Option value={1}>仅CMS后台</Option>
              <Option value={2}>仅C端前台</Option>
              <Option value={3}>CMS后台和C端前台</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              添加
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 停用用户模态框 */}
      <Modal
        title="停用用户"
        visible={isDisableModalVisible}
        onOk={handleDisableConfirm}
        onCancel={handleDisableCancel}
        afterClose={handleDisableModalClose}
      >
        <Form form={disableForm} layout="vertical">
          <Form.Item
            name="disableReason"
            label="停用原因"
            rules={[{ required: true, message: "请输入停用原因" }]}
          >
            <Input.TextArea
              rows={4}
              onChange={(e) => setDisableReason(e.target.value)}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;
